<script lang="ts" setup>
import {
  ElTable,
  ElInput,
  ElSelect,
  ElOption,
  ElButton,
  ElMessageBox,
  ElMessage,
  ElRow,
  ElCol,
  ElPagination,
} from "element-plus";
import { ref, onMounted, onUnmounted } from "vue";
import { Plus } from "@vben/icons";
import { router } from "#/router";
import { getDroneList, deleteDrone } from "#/api/sys/equipment";
import { useDebounceFn } from "@vueuse/core";

const status = ref("");
const droneName = ref("");
const tableData = ref([]);
let currentPage = ref(1);
let pageSize = ref(10);
let total = ref(0);

// 添加刷新数据的监听器
const handleRefresh = () => {
  search();
};

const spaceInput = (value: string) => {
  // 过滤空格
  droneName.value = value.replace(/\s+/g, "");
};
const search = async () => {
  const params = {
    droneName: droneName.value,
    status: status.value,
    currentPage: currentPage.value,
    pageSize: pageSize.value,
  };
  const { data } = await getDroneList(params);
  if (data.records.length > 0) {
    data.records.map((item) => {
      item.status = item.status + "";
      // 测试
      item.maintenance = '正在保养'
    });
    tableData.value = data.records;
    total.value = data.total;
  } else {
    tableData.value = [];
    total.value = 0;
  }
};
const debouncedSearch = useDebounceFn(search, 500);
const resetForm = () => {
  status.value = "";
  droneName.value = "";
  currentPage.value = 1;
  search();
};

const statusOptions = [
  {
    label: "作业中",
    value: 1,
  },
  {
    label: "待命",
    value: 2,
  },
  {
    label: "离线",
    value: 3,
  },
];

const addItem = () => {
  router.push({
    name: "UvaAddEdit",
  });
};
const editItem = (row) => {
  router.push({
    name: "UvaAddEdit",
    query: {
      id: row.id,
    },
  });
};
const detailItem = (row) => {
  router.push({
    name: "UvaDetail",
    query: {
      id: row.id,
    },
  });
};
const delItem = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定删除无人机【${row.droneName}】吗？`,
      "删除确认",
      {
        type: "warning",
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        beforeClose: async (action, instance, done) => {
          if (action === "confirm") {
            instance.confirmButtonLoading = true;
            try {
              await deleteDrone(row.id);
              done();
            } catch (error) {
              instance.confirmButtonLoading = false;
            }
          } else {
            done();
          }
        },
      }
    );
    ElMessage.success("删除成功");
    search();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error(`删除失败: ${error.message || "未知错误"}`);
      console.error("删除无人机失败:", error);
    }
  }
};

const handleSizeChange = (val) => {
  pageSize.value = val;
  search();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  search();
};

onMounted(() => {
  search();
  // 添加事件监听器
  window.addEventListener('refreshUvaList', handleRefresh);
});

// 组件卸载时移除事件监听器
onUnmounted(() => {
  window.removeEventListener('refreshUvaList', handleRefresh);
});
</script>

<template>
  <div class="page">
    <div class="search">
      <!-- <ElRow>
        <ElCol :xs="24" :sm="24" :md="20" :lg="20" :xl="20" class="searchCol">
          <div class="searchForm">
            <div>
              <span>无人机名称：</span>
              <ElInput
                v-model="droneName"
                style="width: 240px; margin-right: 20px"
                placeholder="请输入无人机名称"
                @input="spaceInput"
                clearable
              />
            </div>
            <div>
              <span>无人机状态：</span>
              <ElSelect
                v-model="status"
                placeholder="请选择无人机状态"
                style="width: 240px; margin-right: 20px"
                @change="search()"
              >
                <ElOption
                  v-for="item in statusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </ElSelect>
            </div>
            <div class="searchBtn">
              <ElButton type="primary" @click="debouncedSearch">查询</ElButton>
              <ElButton @click="resetForm">重置</ElButton>
            </div>
          </div>
        </ElCol>
        <ElCol :xs="24" :sm="24" :md="4" :lg="4" :xl="4" class="searchCol">
          <div style="float: right">
            <ElButton type="primary" @click="addItem">添加</ElButton>
          </div>
        </ElCol>
      </ElRow> -->
    </div>

    <ElTable :data="tableData" stripe style="width: 100%" row-key="id">
      <ElTable.TableColumn prop="droneName" label="无人机名称" align="center" />
      <ElTable.TableColumn
        prop="droneBrand"
        label="无人机品牌"
        align="center"
      />
      <ElTable.TableColumn
        prop="droneModel"
        label="无人机型号"
        align="center"
      />
      <ElTable.TableColumn prop="airportName" label="关联机场" align="center" />
      <!-- <ElTable.TableColumn
        prop="feishouUserName"
        label="关联飞手"
        align="center"
      /> -->
      <ElTable.TableColumn prop="status" label="状态" align="center" width="80">
        <template #default="scope">
          <span v-if="scope.row.status == '作业中'" style="color: #67c23a"
            >作业中</span
          >
          <span v-if="scope.row.status == '离线'" style="color: #f56c6c"
            >离线</span
          >
          <span v-if="scope.row.status == '待命'" style="color: #e6a23c"
            >待命</span
          >
        </template>
      </ElTable.TableColumn>
      <ElTable.TableColumn
        prop="droneBatteryMaintenanceState"
        label="保养信息"
        align="center"
        width="90"
      >
        <template #default="scope">
          <span
            v-if="scope.row.droneBatteryMaintenanceState == '0'"
            style="color: #67c23a"
            >无需保养</span
          >
          <span v-if="scope.row.droneBatteryMaintenanceState == '1'" style="color: #f56c6c"
            >待保养</span
          >
          <span
            v-if="scope.row.droneBatteryMaintenanceState == '正在保养'"
            style="color: var(--el-color-primary)"
            >正在保养</span
          >
        </template>
      </ElTable.TableColumn>
      <ElTable.TableColumn fixed="right" label="操作" align="center">
        <template #default="scope">
          <el-button
            link
            type="primary"
            size="small"
            @click="detailItem(scope.row)"
          >
            详情
          </el-button>
          <el-button
            link
            type="primary"
            size="small"
            @click="editItem(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            link
            type="primary"
            size="small"
            @click="delItem(scope.row)"
            >删除</el-button
          >
        </template>
      </ElTable.TableColumn>
    </ElTable>
    <div class="pagination">
      <ElPagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 80, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>
<style scoped>
.page {
  height: calc(100vh - 188px);
  overflow: scroll;
}

.searchForm {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  font-size: 14px;
}

.el-table {
  margin-top: 20px;
}

:deep(.el-table th) {
  background: #f5f7fa !important;
}

.el-table--fit {
  height: calc(100vh - 300px);
}

:deep(.el-table--fit .el-table__inner-wrapper:before) {
  width: 0 !important;
}

.pagination {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  width: 100%;
  padding: 20px 24px 0px 16px;
}

@media (max-width: 950px) {
  .searchForm {
    flex-direction: column;
    align-items: flex-start;
  }

  .searchBtn {
    margin-top: 10px;
  }
}
</style>
